var net = require('net')
var server = net.createServer()
var sockets = []
var ws = require('nodejs-websocket')
var crypto=require('crypto')
var PORT = 23333
function in_array(stringToSearch, arrayToSearch) {
    for (s = 0; s < arrayToSearch.length; s++) {
        thisEntry = arrayToSearch[s].toString();
        if (thisEntry == stringToSearch) return true;
    }
    return false;
}
function sendmsg(socket) {
    socket.send(JSON.stringify({ code: "msg", nick: data.nick, data: data.data }))
}
function sendjoin(socket) {
    socket.send(JSON.stringify({ code: "join", nick: data.nick, data: '' }));
}
function sendleave(socket) {
    socket.send(JSON.stringify({ code: "leave", nick: data.nick, data: '' }));
}
function NewPass(nick) {
    return "233333";
    return md5(nick);
}
function md5 (text) {
  return crypto.createHash('md5').update(text).digest('hex');
};
var nicks = [];
var server = ws.createServer(function (socket) {
    console.log('New connection')
    sockets.push(socket);
    socket.on("text", function (dat) {
        console.log("Received" + dat)
        if (JSON.parse(dat)) {
            data = JSON.parse(dat);
            if (typeof data.nick != undefined) {
                if (data.nick != null) {
                    if (data.code == "msg")
                        if (in_array(data.nick, nicks))
                            sockets.forEach(sendmsg);
                    if (data.code == "join") {
                        if (!in_array(data.nick, nicks))
                            if (data.nick.substring(1,data.nick.length-1)=='#') {
                                socket.send(JSON.stringify({ code: "success", nick: data.nick, data: '' }));
                                for (i in nicks)
                                    socket.send(JSON.stringify({ code: "join", nick: nicks[i], data: "" }));
                                sockets.forEach(sendjoin);
                                nicks.push(data.nick);
                            } else {
                                socket.send(JSON.stringify({ code: "needpass", nick: data.nick, data: '请输入当前用户的密码：' }));
                            }
                        else {
                            socket.send(JSON.stringify({ code: "fail", data: "此名片已经有人使用", nick: data.nick }));
                        }
                    }
                    if (data.code == "setpass") {
                        if (data.data == NewPass(data.nick)) {
                            socket.send(JSON.stringify({ code: "success", nick: data.nick, data: '' }));
                            sockets.forEach(sendjoin);
                            nicks.push(data.nick);
                        } else {
                            socket.send(JSON.stringify({ code: "fail", nick: data.nick, data: '' }));
                        }
                    }
                    if (data.code == "keep-alive") 
                        socket.send(JSON.stringify({code:"keep-alive",data:'',nick:data.nick}));
                }
            }
        }
    })
    socket.on("close", function (code, reason) {
        console.log("connection closed")
        var index = sockets.indexOf(socket)
        sockets.splice(index, 1)
        if (typeof data.nick != undefined) {
            var index = nicks.indexOf(data.nick)
            nicks.splice(index, 1);
            sockets.forEach(sendleave);
        }
    })
    socket.on("error", function (err) {
        console.log("handle err")
        console.log(err)
    })
}).listen(PORT)
console.log('Chat server listening on port ' + PORT)